package info

import (
	"net"
	"os"
	"runtime"
	"strings"
)

type HostInfo struct {
	Hostname string `json:"hostname"`
	IP       string `json:"ip"`
	OS       string `json:"os"`
	Arch     string `json:"arch"`
}

func GetHostInfo() *HostInfo {
	hostname, _ := os.Hostname()
	ip := GetIP()
	return &HostInfo{
		Hostname: hostname,
		IP:       ip,
		OS:       runtime.GOOS,
		Arch:     runtime.GOARCH,
	}
}

func GetIP() string {
	//获取所有IP地址
	var address []string
	addrs, _ := net.InterfaceAddrs()
	for _, addr := range addrs {
		if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			if ipnet.IP.To4() != nil {
				address = append(address, ipnet.IP.String())
			}
		}
	}
	if len(address) > 1 {
		return strings.Join(address, ",")
	}
	if len(address) == 1 {
		return address[0]
	}
	return ""
}
